import store from '../store'
import * as domains from './env';
import fetch from './fetch';
import * as Util from './utils';
import router from '@/router';

/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = name => {
  if (!name) return;
  return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return;
  window.localStorage.removeItem(name);
}
/**
 * 数组去重
 * @param {*} arr 
 */
export const unique = (arr) => {
  return [...new Set(arr)]
}

/**
 * 获取json接口中有用字段
 * @param {*} url 
 */
export const getPageParam = url => {
  var rg = /([^\/]+)(?=-\d*)|([^\/]+)(?=\.json)/
  return url.match(rg)[0];
}

/**
 * 动态加载js
 */
export const loadScript = (url, callback) => {
  // var script = document.createElement("script");
  // script.type = "text/javascript";
  // script.src = url;
  // document.body.appendChild(script);
  let head = document.getElementsByTagName('head')[0];
  let script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = url;
  script.onload = script.onreadystatechange = function () {
    if ((!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete')) {
      callback && callback();
      script.onload = script.onreadystatechange = null;
      if (head && script.parentNode) {
        head.removeChild(script);
      }
    }
  };
  head.insertBefore(script, head.firstChild);
}

/**
 * 动态加载css文件
 */
export const loadStyles = url => {
  var link = document.createElement("link");
  link.type = "text/css";
  link.rel = "stylesheet";
  link.href = url;
  document.getElementsByTagName("head")[0].appendChild(link);
}

export const parseURL = url => {
  var a = document.createElement('a');
  a.href = url;
  return {
    source: url,
    protocol: a.protocol.replace(':', ''),
    host: a.hostname,
    port: a.port,
    query: a.search,
    params: (function () {
      var ret = {},
        seg = a.search.replace(/^\?/, '').split('&'),
        len = seg.length,
        i = 0,
        s;
      for (; i < len; i++) {
        if (!seg[i]) {
          continue;
        }
        s = seg[i].split('=');
        ret[s[0]] = s[1];
      }
      return ret;
    })(),
    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
    hash: a.hash.replace('#', ''),
    path: a.pathname.replace(/^([^\/])/, '/$1'),
    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
    segments: a.pathname.replace(/^\//, '').split('/')
  };
}

/* Cookie操作 */
export const setCookie = (f, h, day) => {
  var e = day || 60;
  var g = new Date;
  g.setTime(g.getTime() + e * 24 * 60 * 60 * 1000);
  document.cookie = f + "=" + encodeURIComponent(h) + "; path=/; expires=" + g.toGMTString();
}

export const getCookie = (c) => {
  var d = document.cookie.match(new RegExp("(^| )" + c + "=([^;]*)(;|$)"));
  if (d != null) {
    return decodeURIComponent(d[2]);
  }
  return null;
}

/* 取URL参数 */
export const getUrlParam = (p) => {
  var search = location.search;

  if (search == "") {
    return null;
  }

  var params = search.substr(1).split('&'),
    obj = {};

  for (var i = 0; i < params.length; i++) {
    var parts = params[i].split('=');
    obj[parts[0]] = parts[1];
  }

  return decodeURIComponent(obj[p] || '');
}
/**
 * 设置选择的地址的cookie
 */
export const setSelectedPositionCookie = (p) => {
  setCookie('xd_cityCode', p.cityCode);
  setCookie('xd_cityName', p.cityName);
  setCookie('xd_storeLocation', p.storeLocation);
  setCookie('xd_storeCode', p.storeCode);
  setCookie('xd_storeName', p.storeName);
  setCookie('xd_poiId', p.poiId);
  setCookie('xd_poiName', p.poiName);
  setCookie('xd_areaId', p.areaId || 0);
}

/* 微信登录 */
export const wxLogin = () => {
    if (store.state.client.app) {
        location.href = 'https://passport.suning.com/ids/login?trust_redirect=' + encodeURIComponent(location.href);
    }
    else {
        location.href = domains.mobts + encodeURIComponent(location.href);
    }
}

// 设置微信title
export const SetTitle = (title) => {
  if (title === undefined) {
    return
  }
  document.title = title
  var mobile = navigator.userAgent.toLowerCase()
  if (/iphone|ipad|ipod/i.test(mobile)) {
    var iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    var iframeCallback = function () {
      setTimeout(function () {
        iframe.removeEventListener('load', iframeCallback)
        document.body.removeChild(iframe)
      }, 0)
    }
    iframe.addEventListener('load', iframeCallback)
    document.body.appendChild(iframe)
  }
}

export const setErrorImg = () => {
  console.log("imgimgimgimg")
}

export const getTelReplace = (number) => {
    if (!number) {
        return '';
    }
    var tel = number.substr(0,3) + "****" + number.substr(7,4)
    return tel;
}

export const routeTo = (href) => {

    var search = href.substr(href.indexOf('?')),
        params = search.substr(1).split('&'),
        obj = {}, jumpTo = '';

    for (var i = 0; i < params.length; i++) {
        var parts = params[i].split('=');
        obj[parts[0]] = parts[1];
    }

    // 根据snstoreTypeCode确定跳转地址
    var p1 = obj['snstoreTypeCode'],
        p2 = obj['snstoreId'],
        p3 = obj['extId'];

    if (p1) {
        switch(p1) {
            case '1001': jumpTo = '/'; break;
            case '1002':
                if (/^1/ig.test(p3)) {
                    jumpTo = p2 + (p2.indexOf('?')>0 ? '&' : '?') + 'minicart=true';
                }
                else {
                    jumpTo = p2;
                }
                break;
            // case '1003': jumpTo = '/detail.html?cmmdtyCode=' + p2; break;
            case '1003': 
                let reg1 = /_/
                let a
                if (reg1.test(p2)){
                  a = p2.splice('_');
                  jumpTo = `/detail/${a[0]}/${a[1]}`; break;
                }else {
                  a = p2
                  jumpTo = `/detail/${a}/0000000000`; break;
                }
            //case '1004': jumpTo = '/'; break;
            case '1005': jumpTo = '/'; break;
            case '1006': jumpTo = '/orders'; break;
            case '1007': jumpTo = 'http://s.suning.com/report/custom/m/cmws.htm'; break;
            case '1008':
                if (!p2) {
                    jumpTo = '/list';
                    break;
                }
                if (p3 == '1') {
                    jumpTo = `/shoplist/${p2}`;
                    break;
                }
                if (p3 == '0') {
                    jumpTo = '/list';
                    break;
                }
                break;
            case '1009': jumpTo = '/cart1'; break;
            case '1010': jumpTo = '/my'; break;
            // default:
            //     return !$('<div class="apptip"><div class="apptip-main"><a href="' + domains.xd + '/dlapp/jump.html" class="btn"></a><a href="javascript:void(0);" class="close"></a></div></div>')
            //         .appendTo('body')
            //         .on('click', '.close', function() {
            //             $('.apptip').remove();
            //         });

        }
        return jumpTo;
        // location.href = jumpTo;
    }
}